//
//  priterModule.m
//  fetailAdmin
//
//  Created by eval on 2018/8/25.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "UsaPayModule.h"
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import "PaymentEngineTransactionResponse.h"

@implementation UsaPayModule

NSString* EVENT_NAME_USAPAY = @"usaPayEvent";
MViewController *view;

RCT_EXPORT_MODULE(UsaPayModule);

- (NSArray<NSString *> *)supportedEvents{
  return @[EVENT_NAME_USAPAY];
}
- (instancetype)init
{
  self = [super init];
  if (self) {
//    self.middlewareSetting = [PaymentEngineMiddlewareSettings getInstance];
//    self.middlewareSetting.isTipAdjustSupported = true;
//    self.middleware = [PaymentEngineMiddleware getInstance];
//    
//    /**
//     * The mode can be either sandbox or production
//     * If developer wants to test on our sandbox server, they will set the currentMode to sandbox
//     * It's not case sensitive
//     */
//    self.middlewareSetting.currentMode = @"sandbox";
//    self.middlewareSetting.sourceKey = @"_iOunDQQLRKNta66hjJhfBNiD1WU6EV7";
//    self.middlewareSetting.pinNum = @"123456";
//    
//    /**
//     * The below setting values are optional, by default they are set to false
//     * This is used to print out the middleware debugging log during development
//     */
//    self.middlewareSetting.enableDebugLog = true;
//    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateResultLog:) name:MiddlewareLogNotification object:nil];
//    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userFlowNotif:) name:MiddlewareFlowNotification object:nil];
//    
//    /**
//     * Initialize the middleware class with the device we will be using
//     */
//    [self.middleware setDevice:@"castle" :self];
  }
  return self;
}
RCT_EXPORT_METHOD(initial:(NSDictionary*) data){
//  if([self.middleware isDeviceOnline])
//  {
//    [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"initialed"}];
//    return ;
//  }
//  self.middlewareSetting = [PaymentEngineMiddlewareSettings getInstance];
//  self.middlewareSetting.isTipAdjustSupported = true;
//  self.middleware = [PaymentEngineMiddleware getInstance];
//
//  self.middlewareSetting.currentMode = data[@"currentMode"];
//  self.middlewareSetting.sourceKey = data[@"sourceKey"];
//  self.middlewareSetting.pinNum = data[@"pinNum"];
//  self.middlewareSetting.enableDebugLog = data[@"enableDebugLog"];
//  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateResultLog:) name:MiddlewareLogNotification object:nil];
//  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userFlowNotif:) name:MiddlewareFlowNotification object:nil];
//  //zheli haoxian yeshi shezhi。
//  [self.middleware setDevice:@"castle" :self];
//
//  self.middleware.delegate = self;
//  [self.middleware connectDevice];
  view = [[MViewController alloc] init];
  [view inital];
//  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"initial",@"data":[self.middleware getDeviceInfo]}];
}



RCT_EXPORT_METHOD(transction:(NSDictionary*) data:(RCTResponseSenderBlock)callback){
//  if([self.middleware isDeviceOnline])
//  {
//    NSMutableDictionary *transDict = [NSMutableDictionary new];
//    [transDict setObject:data[@"command"] forKey:@"command"];
//    [transDict setObject:data[@"amount"] forKey:@"amount"];
//    [transDict setObject:data[@"invoice"] forKey:@"invoice"];
//    [transDict setObject:data[@"description"] forKey:@"description"];
    
//    dispatch_sync(dispatch_get_main_queue(),^{
//      NSMutableDictionary *transDict = [NSMutableDictionary new];
//      [transDict setObject:@"cc:sale" forKey:@"command"];
//      [transDict setObject:@"0.10" forKey:@"amount"];
//      [transDict setObject:@"10000" forKey:@"invoice"];
//      [transDict setObject:@"This is my first middleware transaction" forKey:@"description"];
//      [self.middleware startTransaction:transDict];
//      callback(@[[NSNull null]]);
//    });
//    __weak typeof(self) weakSelf = self;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//      NSMutableDictionary *transDict = [NSMutableDictionary new];
//      [transDict setObject:@"cc:sale" forKey:@"command"];
//      [transDict setObject:@"0.10" forKey:@"amount"];
//      [transDict setObject:@"10000" forKey:@"invoice"];
//      [transDict setObject:@"This is my first middleware transaction" forKey:@"description"];
//      //这里发送出去的时候，数据是有的，回调提示发送数据为nil。
//      //这里，发送出去的数据是有的。transDict 新建的，连接也是正常的，他内部处理的时候，告诉我事务的数据为nil。同样的代码，在viewcontrol中可以，
//      //放过来就可以执行。硬件那边也会提示成功。
//      [weakSelf.middleware startTransaction:transDict];
////      callback(@[[NSNull null]]);
////    });
//    NSMutableDictionary *transDict = [NSMutableDictionary new];
//    [transDict setObject:@"cc:sale" forKey:@"command"];
//    [transDict setObject:@"0.10" forKey:@"amount"];
//    [transDict setObject:@"10000" forKey:@"invoice"];
//    [transDict setObject:@"This is my first middleware transaction" forKey:@"description"];
      [view startTransaction];
    //这里发送出去的时候，数据是有的，回调提示发送数据为nil。
    //这里，发送出去的数据是有的。transDict 新建的，连接也是正常的，他内部处理的时候，告诉我事务的数据为nil。同样的代码，在viewcontrol中可以，
    //放过来就可以执行。硬件那边也会提示成功。
//    [self.middleware startTransaction:[transDict mutableCopy]];
//  }
//  else
//  {
//    callback(@[@"初始化失败"]);
//  }
}

/**
 * The delegate notification method prints out all the middleware debugging logs
 */
-(void)updateResultLog :(NSNotification *)notif
{
  NSString *logString = [notif object];
  //这个方法是发送到js端端。是一个回调。我在js端知道。
  NSLog(@"logString%@",logString);
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"log",@"data":logString}];
}

/**
 * The delegate notification method prints out the transaction flow logs
 */
-(void)userFlowNotif :(NSNotification *)notif
{
  NSString *userFlowLog = [notif object];
  NSLog(@"userFlowLog%@",userFlowLog);
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"flow",@"data":[notif userInfo]}];
}

-(void)readDeviceInfoComplete:(NSDictionary *)deviceInfoDict
{
  NSLog(@"read device completed: %@", deviceInfoDict);
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"readDeviceInfoComplete",@"data":deviceInfoDict}];
}

-(void)transactionComplete :(PaymentEngineTransactionResponse *)transResponse
{
  if(transResponse != nil){
    [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"transactionComplete",@"data":transResponse}];
  }
}

-(void)returnReceiptCompleted :(NSString *)receiptValue
{
    [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"returnReceiptCompleted",@"data":receiptValue}];
}

-(void)captureSignatureComplete :(PaymentEngineTransactionResponse *)transResponse
{
  
  if(transResponse != nil)
  {
    [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"captureSignatureComplete",@"data":transResponse}];
  }
  
}
-(void)deviceConnected{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"deviceConnected"}];
}
/*!
 @brief Delegate method, it will get call when we start to update the terminal config
 */
-(void)startUpdatingTerminal{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"deviceConnected",@"data":@""}];
}

/*!
 @brief Delegate method, it will get call once we finish updating all the terminal config
 */
-(void)updateTerminalConfigComplete{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"updateTerminalConfigComplete",@"data":@""}];
}

/*!
 @brief Delegate method for getMerchantCapabilities
 @param merchantCapDict - Dictionary that holds information about the merchant and the features they support
 */
-(void)getMerchantCapabilitiesComplete: (NSDictionary *)merchantCapDict{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"getMerchantCapabilitiesComplete",@"data":merchantCapDict}];
}

/*!
 * The delegate method gets called when adjust transaction is completed
 * @param transResponse - Contains all the transaction information returned from the gateway
 */
-(void)adjustTranstionComplete :(PaymentEngineTransactionResponse *)transResponse{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"adjustTranstionComplete",@"data":transResponse}];
};

/*!
 @brief Delegate method for print, this is an optional delegate method if user wants to see print error
 @param msg - returns the error message
 */
-(void)printCompleted:(NSString *)msg{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"printCompleted",@"data":msg}];
};
/*
 @brief delegate method, gets call once barcode scan is completed
 @param barcode - returns the scanned barcode
 @param errorMsg - If there is an error, return what the error is,
 */
-(void)barcodeScanCompleted :(NSString *)barcode :(NSString *)errorMsg{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"printCompleted",@"data":errorMsg}];
};

/*
 @brief delegate method, gets call once we obtain a timeout duration from the device
 @param seconds - returns the timeout duration in seconds
 */
-(void)getDeviceTimeoutCompleted :(int) seconds{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"printCompleted"}];
};

/*!
 @brief Delegate method for device disconnected. The method gets called when the device is disconnected
 */
-(void)deviceDisconnected{
  [self sendEventWithName:EVENT_NAME_USAPAY body:@{@"type":@"deviceDisconnected"}];
}


@end;
